import datetime
import json
from html import unescape, escape

from app.utils.time_util import timestamp2datetime
from exts import db
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, BadSignature
from urllib.parse import urlencode
from app import app


class QUserInfo(db.Model):
    __tablename__ = 'qiao_user_info'
    username = db.Column(db.String(255), primary_key=True)
    password = db.Column(db.String(255), unique=False)
    role = db.Column(db.Integer, unique=False)
    name = db.Column(db.String(255), unique=False)
    mail = db.Column(db.String(255), unique=False)
    reg_date = db.Column(db.String(255), unique=False)
    competence = db.Column(db.TEXT)

    def to_dict(self):
        '''将对象转换为字典数据'''
        reDict = {
            "username": self.username,
            "role": self.role,
            "name": self.name,
            "mail": self.mail,
            "reg_date": self.reg_date,
            "competence": json.loads(self.competence or '[]')
        }
        return reDict
        # 获取token，时长秒

    def generate_auth_token(self, expiration=3600 * 24):
        s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps(self.username)

        # 通过token解析用户信息

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            username = s.loads(token)
        except SignatureExpired:
            print('SignatureExpired', SignatureExpired)
            return None  # valid token, but expired
        except BadSignature:
            print('BadSignature', BadSignature)
            return None  # invalid token
        except Exception as e:
            print('Error: ', e)
            return None
        user = QUserInfo.query.get(username)
        return user

    def hash_password(self, password):  # 加密
        self.password = pwd_context.encrypt(password)

    def verify_password(self, password):  # 解密
        try:
            return pwd_context.verify(password, self.password)
        except Exception as e:
            print(e)
            return None


class QUserLoginHistory(db.Model):
    __tablename__ = 'qiao_user_login_history'
    id = db.Column(db.Integer, primary_key=True)
    userid = db.Column(db.String(255), unique=False)
    time = db.Column(db.Integer, unique=False)
    ip = db.Column(db.String(255), unique=False)
    status = db.Column(db.String(255), unique=False)

    def to_dict(self):
        '''将对象转换为字典数据'''
        reDict = {
            "id": self.id,
            "userid": self.userid,
            "time": timestamp2datetime(self.time),
            "ip": self.ip,
            "status": self.status,
        }
        return reDict
